import React, { Component } from 'react'
import NavHeader from '../../components/Common/NavHeader'
import { Link } from 'react-router-dom'
import { Toast } from 'antd-mobile'
import { getHouseSource, getHouseInfo } from '../../network/map'
import './index.scss'
import { BASE_URL } from '../../assets/js/constant'
const BMapGL = window.BMapGL
// 覆盖物样式
const labelStyle = {
  cursor: 'pointer',
  border: '0px solid rgb(255,0,0)',
  padding: '0px',
  whiteSpace: 'nowrap',
  fontSize: '12px',
  color: '#fff',
  textAlign: 'center'
}
export default class Map extends Component {
  state = {
    // 小区下的房源列表
    housesList: [],
    // 表示是否展示房源列表
    isShowList: false
  }

  componentDidMount() {
    this.createMap()
  }

  // 初始化地图
  createMap = () => {
    const map = new BMapGL.Map('container')
    this.map = map
    const { label, value } = JSON.parse(localStorage.getItem('hkzf_city'))
    const myGeo = new BMapGL.Geocoder()
    myGeo.getPoint(label, async point => {
      if (point) {
        map.centerAndZoom(point, 11)
        map.addControl(new BMapGL.ScaleControl()) //标尺
        map.addControl(new BMapGL.ZoomControl()) // 放大缩小

        this.renderOverlays(value)
      }
    }, label)

    // 添加地图移动事件
    this.map.addEventListener('movestart', () => {
      if (this.state.isShowList) {
        this.setState({ isShowList: false })
      }
    })
  }

  // 渲染覆盖物入口
  renderOverlays = async (id) => {
    try {
      Toast.loading('加载中......', 0, null, false)
      const { body: data } = await getHouseSource(id)
      Toast.hide()
      const { nextZoom, type } = this.getTypeAndZoom()
      // console.log(nextZoom, type)
      data.forEach(item => {
        this.createOverlays(item, nextZoom, type)
      })
    } catch (error) {
      Toast.hide()

    }
  }

  // 创建覆盖物
  createOverlays = (data, zoom, type) => {
    const {
      coord: { longitude, latitude },
      label: areaName,
      count,
      value
    } = data
    const areaPoint = new BMapGL.Point(longitude, latitude)

    if (type === 'circle') {
      this.createCicle(areaPoint, areaName, count, value, zoom)
    } else {
      this.createRect(areaPoint, areaName, count, value)
    }
  }

  // 创建区、镇覆盖物
  createCicle = async (point, name, count, id, zoom) => {
    // 初始化覆盖物
    const label = new BMapGL.Label('', {
      position: point,
      offset: new BMapGL.Size(-35, -35)
    })
    // 设置id
    label.id = id

    // 设置内容
    label.setContent(`
            <div class="bubble">
              <p class="name">${name}</p>
              <p>${count}套</p>
            </div>
        `)

    // 设置样式
    label.setStyle(labelStyle)

    // 添加点击事件
    label.addEventListener('click', () => {
      // 继续渲染下一级房源信息
      this.renderOverlays(id)

      this.map.centerAndZoom(point, zoom)
      setTimeout(() => this.map.clearOverlays(), 0)
    })

    // 添加覆盖物
    this.map.addOverlay(label)

  }

  // 创建小区覆盖物
  createRect = (point, name, count, id,) => {
    // 初始化覆盖物
    const label = new BMapGL.Label('', {
      position: point,
      offset: new BMapGL.Size(-50, -28)
    })
    // 设置id
    label.id = id

    // 设置内容
    label.setContent(`
        <div class="rect">
          <span class="housename">${name}</span>
          <span class="housenum">${count}套</span>
          <i class="arrow"></i>
        </div>
    `)

    // 设置样式
    label.setStyle(labelStyle)

    // 添加点击事件
    label.addEventListener('click', async (e) => {
      Toast.loading('加载中......', 0, null, false)
      const res = await getHouseInfo(id)
      Toast.hide()
      // 移动地图
      const target = e.domEvent.changedTouches[0]
      this.map.panBy(
        window.innerWidth / 2 - target.clientX,
        (window.innerHeight - 330) / 2 - target.clientY
      )

      this.setState({ housesList: res.body.list, isShowList: true })

    })

    // 添加覆盖物
    this.map.addOverlay(label)
  }

  // 获取需要渲染的大小和类型
  getTypeAndZoom = () => {
    const zoom = this.map.getZoom()
    let nextZoom, type
    if (zoom === 11) {
      nextZoom = 13
      type = 'circle'
    } else if (zoom === 13) {
      nextZoom = 15
      type = 'circle'
    } else {
      type = 'rect'
    }
    return { nextZoom, type }
  }

  // 渲染房源信息
  renderHousesList = () => {
    return this.state.housesList.map(item => {
      return (
        <div className="house" key={item.houseCode}>
          <div className="imgWrap">
            <img src={BASE_URL + item.houseImg} alt="" />
          </div>
          <div className="content">
            <h3 className="title">{item.title}</h3>
            <div className="wadw">
              <div className="desc">{item.desc}</div>
            </div>
            <div>
              {item.tags.map((tag, index) => {
                const tagName = `tag ${'tag' + (1 + index)}`
                return <span key={tag} className={tagName}>{tag}</span>
              })}
            </div>
            <div className="price">
              <span className="priceNum">{item.price}元/月</span>
            </div>
          </div>
        </div>
      )
    })

  }

  render() {
    return (
      <div className="map">
        <NavHeader>地图找房</NavHeader>
        {/* 地图容器 */}
        <div id="container"></div>

        {/* 房源列表 */}
        <div className={`houseList${this.state.isShowList ? ' show' : ''}`}>
          {/* 导航栏 */}
          <div className="titleWrap">
            <h1 className="listTitle">房屋列表</h1>
            <Link className="titleMore" to="/home/list">
              更多房源
            </Link>
          </div>

          <div className="houseItems">
            {/* 房屋结构 */}
            {this.renderHousesList()}
          </div>
        </div>
      </div>
    )
  }
}
